import React, {Component} from 'react';
import {Button, FlatList, Image, NativeModules, StatusBar, StyleSheet, Text, ToastAndroid, View} from 'react-native';
import * as Color from "../../../lib.xjs/constant/Color";
import TouchableItem from "react-navigation/src/views/TouchableItem";
import BizUser from "../../entity/BizUser";
import * as BizConstant from "../../constant/BizContant";
import HttpHelper from "../../../lib.xjs/helper/HttpHelper";
import {UUID} from "../../../lib.xjs/util/UUID";
import {GaquUtil} from "../../util/GaquUtil";
import BottomPop from "../../../lib.xjs/widget/modal/BottomPop";

const ITEM_HEIGHT = 100;

const ic_avatar_default = require('../../../../img/ic_mine_dis.png');

/** 仓体运动记录 */
export default class CabinExerciseList extends Component {

    /** 当前时间 */
    _mDateNow;
    /** data */
    _mFlatList;

    /** 舱体Id */
    mCabinId;
    /** 舱体名称 */
    mCabinName;

    mPopMenu: Array = ['舱体管理', '服务人员'];

    static navigationOptions = (props) => {
        const params = props.navigation.state.params;
        return {
            title: `${params.cabinName}`,
            headerRight: (                        //通过params为按钮绑定increase方法
                <Button onPress={() => params.navigatePress()} title=":"/>
            ),
        };
    };

    componentWillMount() {
        //在static中使用this方法
        this.props.navigation.setParams({navigatePress: () => this._onClickItemBtn()});
    };

    constructor(props) {
        super(props);
        this.state = {
            /** 是否正在刷新 */
            mIsRefresh: false,
            /** 数据源 */
            mDatas: [],
            /** foot提示信息 */
            loadMoreInfo: '正在加载',
        };

        this._mDateNow  = new Date().Format("yyyy-MM-dd hh:mm:ss");
        this.mCabinId   = this.props.navigation.state.params.cabinId;
        this.mCabinName = this.props.navigation.state.params.cabinName;
    }


    componentDidMount(): void {
        this._getDatas(new Date(), 20, false);
    };

    render() {
        return (
            <View style={{flex: 1, backgroundColor: Color.windowWhite}}>
                <StatusBar
                    hidden={false}
                    translucent={false}
                    backgroundColor={Color.colorPrimaryDark}/>

                <FlatList
                    ref={(flatList) => this._mFlatList = flatList}
                    ListEmptyComponent={this._background()}
                    ListFooterComponent={this._footer()}

                    data={this.state.mDatas}
                    renderItem={(item) => {
                        return this._renderItem(item)
                    }}
                    // ItemSeparatorComponent={this._separator}
                    keyExtractor={(item, index) => ("index" + index + item)}

                    refreshing={this.state.mIsRefresh}
                    onRefresh={this._onRefresh}

                    getItemLayout={this.getItemLayout}

                    onEndReachedThreshold={0.000001}
                    onEndReached={this._onReachEnd}
                />
                <HttpHelper ref={'http'}/>
                <BottomPop ref="pop" onClick={(index: number) => this._onClick(index)}/>
            </View>
        );
    }

    /**
     * 可选优化项。但是实际测试中，如果不做该项优化，性能会差很多。
     * 所以强烈建议做此项优化！如果不做该项优化，每个列表都需要事先渲染一次，动态地取得其渲染尺寸，然后再真正地渲染到页面中。
     * 如果预先知道列表中的每一项的高度(ITEM_HEIGHT)和其在父组件中的偏移量(offset)和位置(index)，就能减少一次渲染。
     * 这是很关键的性能优化点
     * @param data
     * @param index
     * @returns {{length: number, offset: number, index: *}}
     */
    getItemLayout = (data, index) => {
        return {length: ITEM_HEIGHT, offset: (ITEM_HEIGHT + 2) * index, index}
    };

    /**
     * 将列表元素和数据结合在一起，生成列表。
     * @param item 是data属性中的每个列表的数据（ Array<object> 中的 object) 。
     */
    _renderItem = (item) => {
        if (item.item.endTime) {
            let diffDayCount        = GaquUtil.getDayDifference(this._mDateNow, item.item.beginTime);   // 天数差
            let diffDayCountText    = GaquUtil.getDiffDayByDate(diffDayCount);                          // 天数差算"今天","昨天","前天"
            let diffDayColor        = GaquUtil.getDiffDayColorByDate(diffDayCount);                     // 天数差算"今天","昨天","前天"文字的颜色
            let orderStatusColor    = GaquUtil.getOrderStatusColor(item.item.status);

            return this._getItemView_NotING(item, diffDayCount, diffDayCountText, orderStatusColor, diffDayColor);
        } else return this._getItemView_ING(item);
    };

    /**
     *
     * @param item
     * @param diffDayCount      指定日期距离今天的天数差
     * @param orderStatusColor  订单状态颜色值
     * @param diffDayColor      指定日期距离今天的天数差对应的颜色值
     * @returns {*}
     * @private
     */
    _getItemView_NotING = (item, diffDayCount, diffDayCountText, orderStatusColor, diffDayColor) => {
        return <View style={styles.item_layout_touch_bg}>
            <TouchableItem onPress={() => this._onClickItem(item)}>
                <View style={styles.item_not_ing}>
                    <View style={styles.item_not_ing_line1}>
                        <View style={{flexDirection:'row', justifyContent: 'flex-start', alignItems: 'center'}}>
                            <Text style={{fontSize: 18, color: Color.black}}>{item.item.realName}</Text>
                            <Text style={[styles.cabin_status_text, {backgroundColor: GaquUtil.getPersonStatusColor(item.item.userStatus)}]}>{GaquUtil.getPersonStatusName(item.item.userStatus)}</Text>
                        </View>

                        <View style={{flexDirection:'row', justifyContent: 'flex-end', alignItems: 'center'}}>
                            <View style={{display: diffDayCount > 2 ? 'none' : 'flex'}}>
                                <Text style={[styles.cabin_status_text_border, {borderColor: diffDayColor}, {color: diffDayColor}]}>{diffDayCountText}</Text>
                            </View>
                            <Text style={[styles.cabin_status_text_border, {borderColor: orderStatusColor}, {color: orderStatusColor}]}>{GaquUtil.getOrderStatusName(item.item.status)}</Text>
                        </View>
                    </View>

                    <View style={[styles.item_not_ing_line1, {marginTop: 5}]}>
                        <Text style={{fontSize: 14}}>花费</Text>
                        <Text style={{fontSize: 14}}>{item.item.money}元</Text>
                    </View>

                    <View style={styles.item_not_ing_line1}>
                        <Text style={{fontSize: 14}}>运动时间</Text>
                        <Text
                            style={{fontSize: 14}}>{GaquUtil.getTimeDifference(item.item.beginTime, item.item.endTime)}分钟</Text>
                    </View>

                    <View style={styles.item_not_ing_line1}>
                        <Text style={{fontSize: 14}}>{item.item.beginTime}</Text>
                        <Text style={{fontSize: 14}}> — </Text>
                        <Text style={{fontSize: 14}}>{item.item.endTime}</Text>
                    </View>
                </View>
            </TouchableItem>
        </View>
    };

    _getItemView_ING = (item) => {
        return <View style={styles.item_layout_touch_bg}>
            <TouchableItem onPress={() => this._onClickItem(item)}>
                <View style={[styles.item_ing]}>

                    <View style={styles.content_title}>
                        <View style={{height: '80%', width:8, backgroundColor: Color.colorPrimaryLight, marginRight: 15,}}/>
                        <Text style={{fontSize: 18, color: Color.black}}>正在运动</Text>
                    </View>

                    <View style={{width: '100%', height: 0.5, backgroundColor: Color.lightGray}}/>

                    <View style={styles.item_ing_line1}>
                        <Image style={styles.item_head}
                               source={item.item.headImg === null ? ic_avatar_default : {uri: item.item.headImg}}
                               resizeMode={Image.resizeMode.center}/>
                        <View style={{flexDirection: 'column', marginLeft: 15, justifyContent: 'center'}}>
                            <Text style={{fontSize: 16}}>{item.item.realName}</Text>
                            <Text style={{fontSize: 16}}>{item.item.mobile}</Text>
                        </View>
                    </View>

                    <View style={{width: '100%', height: 0.5, backgroundColor: Color.lightGray}}/>

                    <View style={{
                        width: '100%',
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        marginVertical: 8,
                    }}>
                        <View style={{
                            flex: 1,
                            flexDirection: 'column',
                            justifyContent: 'center',
                            alignItems: 'flex-start'
                        }}>
                            <Text style={{fontSize: 14}}>开始时间</Text>
                            <Text style={{fontSize: 14}}>{item.item.beginTime} </Text>
                        </View>

                        <View style={{width: 0.5, backgroundColor: Color.lightGray, marginHorizontal: 10,}}/>

                        <View style={{
                            flex: 1,
                            flexDirection: 'column',
                            justifyContent: 'center',
                            alignItems: 'flex-start'
                        }}>
                            <Text style={{fontSize: 14}}>结束时间</Text>
                            <Text style={{fontSize: 14}}>{item.item.endTime} </Text>
                        </View>
                    </View>
                </View>
            </TouchableItem>
        </View>
    };

    /** 分割线 */
    _separator() {
        return <View style={{height: 1, backgroundColor: Color.lightGray}}/>;
    };


    /** 列表为空的背景 */
    _background() {
        return <View style={{flexDirection: 'column', backgroundColor: Color.windowWhite}}>
            <Text style={[styles.txt]}>暂无数据</Text>
        </View>;
    };

    /** 尾 */
    _footer() {
        return <View style={{flexDirection: 'column', backgroundColor: Color.windowWhite}}>
            <View style={{height: 0.5, backgroundColor: Color.lightMoreGray}}/>
            <Text style={[styles.txt]}>{this.state.loadMoreInfo}</Text>
        </View>;
    };

    /** 获取数据 */
    _getDatas(lastTime: Date, count: number, isClear: boolean): void {
        if (!this.refs.http) return;
        let head = BizUser.getHeadParam(true);
        let body = new Map();
        body.set("lastTime", lastTime.Format("yyyy-MM-dd hh:mm:ss"));
        body.set("count", count);
        body.set("cangId", this.mCabinId);

        this.refs.http.setURL(BizConstant.GET_EXERCISE_RECORD_CABIN)
            .setMethod(HttpHelper.GET)
            .setNotiInfo("")
            .setHeadParams(head)
            .setBodyParams(body)
            .setRequestId(UUID.getOne())
            .setListener((responseCode: number, res: Object) => {
                if (responseCode !== HttpHelper.RESPONSE_SUCCESS) return;
                if (!res.data.records) return;

                // 初始化全局变量
                let datas = res.data.records;
                if (!isClear) datas = this.state.mDatas.concat(datas);
                // if (!isClear) datas = [...this.state.mDatas, ...datas];

                this.setState({
                    mDatas: datas,
                    loadMoreInfo: res.data.records.length < 20 ? '---已经到底了---' : '正在加载',
                });
            })
            .setTimeout(10 * 1000)
            .start(false);
    }

    /** 下拉时促发 */
    _onRefresh = () => {
        if (this.state.mIsRefresh) return;
        ToastAndroid.show('正在刷新中.... ', ToastAndroid.SHORT);
        this.setState({
            mIsRefresh: true,
        });

        let timer = setTimeout(() => {
            this.setState({
                mIsRefresh: false,
            });
            this._getDatas(new Date(), 20, true);
            clearTimeout(timer);
        }, 1000)
    };

    /** 拉到底部时促发 */
    _onReachEnd = () => {
        this._getDatas(this._getLastTimeFromList(), 20, false);
    };

    /** 点击列表项(跳转个人运动记录界面) */
    _onClickItem = (item): void => {
        this.props.navigation.navigate('PersonExerciseList', {
            personName: item.item.realName,
            personId: item.item.uid,
            callback: (data) => {
            }
        })
    };

    /** 点击toolbar右键(跳转舱体操作界面) */
    _onClickItemBtn = (): void => {
        this._showPop();
    };

    /** 从列表中获取最晚的时间 */
    _getLastTimeFromList(): Date {
        let earistTime: Date = new Date();
        for (let item of this.state.mDatas) {
            if (!item.beginTime) continue;
            let timeTarget: Date = new Date(item.beginTime.replace(/-/g, "\/"));
            if (timeTarget < earistTime) earistTime = timeTarget;
        }
        return earistTime;
    }

    /** 显示 */
    _showPop = () => {
        this.refs.pop.setDatasAndShow("请选择操作", this.mPopMenu);
    };

    /** 点击回调 */
    _onClick(index: number) {
        switch (index) {
            case 0: {   // 舱体管理
                this.props.navigation.navigate('CabinOperateMain', {
                    cabinId: this.mCabinId,
                    cabinName: this.mCabinName,
                    callback: (data) => {
                    }
                });
                break
            }

            case 1: {   // 舱体服务人员管理
                this.props.navigation.navigate('CabinSupportStuff', {
                    cabinId: this.mCabinId,
                    cabinName: this.mCabinName,
                    callback: (data) => {
                    }
                });
                break
            }
        }
    };
}

const styles = StyleSheet.create({
    txt: {
        textAlign: 'center',
        textAlignVertical: 'center',
        color: Color.darkGray,
        fontSize: 14,
    },

    item_layout_touch_bg: {
        marginHorizontal: 5,
        marginVertical: 5,
        borderRadius: 4,
        borderWidth: 0.5,
        borderColor: Color.lightMoreGray,
        backgroundColor: Color.windowWhiteLight,
    },

    item_not_ing: {
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        height: ITEM_HEIGHT + 2,
        width: '100%',
        paddingHorizontal: 10,
    },

    item_not_ing_line1: {
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },

    item_ing: {
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        width: '100%',
        paddingHorizontal: 10,
    },

    item_ing_line1: {
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center',
    },

    item_head: {
        height: 100,
        width: 100,
        borderRadius: 100,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },

    content_title: {
        height: 25,
        width: '100%',
        flexDirection:'row',
        justifyContent: 'flex-start',
        alignItems: 'center',
        margin: 5,
    },

    cabin_status_text_border: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        fontSize: 14,
        borderRadius: 4,
        borderWidth: 1,
        paddingHorizontal: 4,
        marginLeft: 3,
    },

    cabin_status_text: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        fontSize: 14,
        borderRadius: 4,
        paddingHorizontal: 4,
        marginLeft: 3,
        color: Color.white,
    },
});
